﻿using System;
using UnityEngine;

public class Hpbar : MonoBehaviour
{
    private float alpha;
    public Color fillColor = Color.red;
    private bool isMainPlayer;
    private float lastShowTime;
    public Life life;
    [SerializeField]
    private Transform m_fillAxis;
    [SerializeField]
    private SpriteRenderer m_fillRenderer;
    public Color mainPlayerFillColor = Color.green;
    private SpriteRenderer[] rens;

    public static Hpbar Create(Life life, float offset)
    {
        Hpbar hpbar = Resources.Load<Hpbar>("Hpbar").CloneGameObjectAsChild<Hpbar>(life.transform, true);
        hpbar.life = life;
        hpbar.transform.localPosition = (Vector3) (Vector3.up * offset);
        return hpbar;
    }

    public void Show(float percent)
    {
        percent = Mathf.Clamp(percent, 0f, 1f);
        this.m_fillRenderer.color = this.fillColor;
        if ((PlayerCharacter.local != null) && (this.life.self == PlayerCharacter.local))
        {
            this.m_fillRenderer.color = this.mainPlayerFillColor;
        }
        this.m_fillAxis.localScale = this.m_fillAxis.localScale.SetX(percent);
        this.alpha = 1f;
        this.lastShowTime = Time.time;
    }

    private void Start()
    {
        this.alpha = 0.01f;
        this.rens = base.GetComponentsInChildren<SpriteRenderer>();
        this.life.onHpChanged += value => this.Show(value / this.life.maxHp);
    }

    private void Update()
    {
        if (this.alpha != 0f)
        {
            if ((Time.time - this.lastShowTime) > 5f)
            {
                this.alpha = Mathf.Lerp(this.alpha, 0f, Time.deltaTime * 8f);
            }
            foreach (SpriteRenderer renderer in this.rens)
            {
                Color color = renderer.color;
                color.a = this.alpha;
                renderer.color = color;
            }
        }
    }
}

